#pragma once

#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
using namespace std;

class udpClient
{
private:
    int _socket;
    uint16_t _port;
    std::string _ip;
public:
    udpClient(string ip,string port)
        :_ip(ip)
        ,_port(stoi(port.c_str()))
    {}

    ~udpClient()
    {}

    void Start()
    {
        //1. 创建socket
        _socket = ::socket(AF_INET,SOCK_DGRAM,0);
        if(_socket < 0)
        {
            cout << "1.创建socket失败" << endl;
            return;
        }
        //2. 设置网络字节序
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = ::inet_addr(_ip.c_str());
        server.sin_port = ::htons(_port);

        while(true)
        {
            string message;
            cout << "Please enter:";
            getline(cin,message);
            ::sendto(_socket,message.c_str(),message.size(),0,(sockaddr*)(&server),sizeof(server));

            char buffer[1024];
            //虽然上面已经有了sockaddr_in server,但是可能不只有一个服务器哦
            struct sockaddr_in tmp;
            socklen_t len = sizeof(tmp);

            int n = ::recvfrom(_socket,buffer,sizeof(buffer)-1,0,(sockaddr*)(&tmp),&len);
            if(n > 0)
            {
                buffer[n] = 0;
                //打印服务器回写的
                std::cout << buffer << std::endl;
            }
        }
    }
};